package org.game.module.core;

import java.util.*;
import java.util.Map.Entry;

import org.bean.AccountInfo;
import org.bean.FunctionSwitchDTO;
import org.bean.GiftCodeDTO;
import org.cache.FunctionSwitchCache;
import org.cfg.ItemRecoverCfg;
import org.cfg.cache.DiscreteDataCfgCache;
import org.cfg.cache.ItemRecoverCfgCache;
import org.constant.*;
import org.error.GameErrorCode;
import org.error.LoginErrorCode;
import org.game.actor.msg.InternalMsg;
import org.game.cache.ServerCache;
import org.game.constant.GameConstant;
import org.game.constant.SessionConstent;
import org.game.db.bean.Formation;
import org.game.db.bean.Hero;
import org.game.db.bean.Player;
import org.game.db.bean.PlayerData;
import org.game.db.cache.FormationCache;
import org.game.db.cache.PlayerCache;
import org.game.db.cache.PlayerDataCache;
import org.game.db.proxy.bean.PlayerDataProxy;
import org.game.db.proxy.bean.PlayerProxy;
import org.game.db.vo.PlayerDataVO.DiscreteVO;
import org.game.db.vo.PlayerDataVO.ResBuyRecordVO;
import org.game.log.LogClientErr;
import org.game.log.LogPlayerAction;
import org.game.log.builder.LogDsp;
import org.game.log.dsp.GoodsDsp;
import org.game.log.dsp.PlayerActionDsp;
import org.game.manager.ItemManager;
import org.game.manager.ItemPackageHelper;
import org.game.manager.PlayerManager;
import org.game.module.fight.FightManager;
import org.game.module.herobo.HeroBO;
import org.game.module.playerbo.PlayerFactory;
import org.game.msgBuilder.FunctionSwitchMsgBuilder;
import org.game.msgBuilder.HeroMsgBuilder;
import org.game.msgBuilder.PlayerMsgBuilder;
import org.game.msgBuilder.ResourceLogMsgBuilder;
import org.game.plugin.event.GameEvent;
import org.game.plugin.event.GameEventPlugin;
import org.game.protobuf.c2s.C2SLoginMsg.EnterGame;
import org.game.protobuf.c2s.C2SLoginMsg.GiftCode;
import org.game.protobuf.c2s.C2SLoginMsg.ReqReconnect;
import org.game.protobuf.c2s.C2SLoginMsg.ReqServerTime;
import org.game.protobuf.c2s.C2SLoginMsg.ReqTestMsg;
import org.game.protobuf.c2s.C2SPlayerMsg;
import org.game.protobuf.c2s.C2SPlayerMsg.ChangeHelpFightHero;
import org.game.protobuf.c2s.C2SPlayerMsg.OperateFormation;
import org.game.protobuf.c2s.C2SPlayerMsg.ReqBuyResources;
import org.game.protobuf.c2s.C2SPlayerMsg.ReqBuyResourcesLog;
import org.game.protobuf.c2s.C2SPlayerMsg.ReqSwitchFormation;
import org.game.protobuf.c2s.C2SPlayerMsg.ReqTargetPlayerInfo;
import org.game.protobuf.c2s.C2SPlayerMsg.SetPlayerInfo;
import org.game.protobuf.c2s.C2SPlayerMsg.Settings;
import org.game.protobuf.s2c.S2CItemMsg;
import org.game.protobuf.s2c.S2CLoginMsg;
import org.game.protobuf.s2c.S2CLoginMsg.GiftCodeRps;
import org.game.protobuf.s2c.S2CLoginMsg.NotMsg;
import org.game.protobuf.s2c.S2CLoginMsg.Notes;
import org.game.protobuf.s2c.S2CLoginMsg.Pong;
import org.game.protobuf.s2c.S2CLoginMsg.RespServerTime;
import org.game.protobuf.s2c.S2CLoginMsg.RespTestMsg;
import org.game.protobuf.s2c.S2CPlayerMsg.BuyResourcesLog;
import org.game.protobuf.s2c.S2CPlayerMsg.FormationInfoList;
import org.game.protobuf.s2c.S2CPlayerMsg.PlayerInfo;
import org.game.protobuf.s2c.S2CPlayerMsg.RepsHelpFightPlayers;
import org.game.protobuf.s2c.S2CPlayerMsg.RespBuyResourcesLog;
import org.game.protobuf.s2c.S2CShareMsg;
import org.game.protobuf.s2c.S2CShareMsg.ChangeType;
import org.game.protobuf.s2c.S2CShareMsg.PlayerSynopsis;
import org.game.protobuf.s2c.S2CShareMsg.RewardsMsg;
import org.game.util.ProtoUnit;
import org.remote.social.RemoteSocialServer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.utils.CommonUtil;
import org.utils.RemoteUtil;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sojoys.artifact.constant.ArtifactErrorCode;
import com.sojoys.artifact.exception.AbstractLogicModelException;
import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.factory.session.ISession;
import com.sojoys.artifact.manager.MessageManager;
import com.sojoys.artifact.manager.PropManager;
import com.sojoys.artifact.manager.ThreadManager;
import com.sojoys.artifact.plugin.dirtyword.DirtyWordsPlugin;
import com.sojoys.artifact.tools.ToolError;
import com.sojoys.artifact.tools.ToolMap;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import com.xiaoleilu.hutool.util.MapUtil;

import akka.actor.ActorRef;

/**
 * @author : DengYing
 * @CreateDate : 2017年7月11日 下午3:30:01
 * @Description ：Please describe this document
 */
public class CoreImpl implements Core,org.game.module.EnterGameHandler {
	
	static final Log log = LogFactory.get(CoreImpl.class);
	
	@Override
	public byte[] enterGame(ISession session, EnterGame enterGame) throws AbstractLogicModelException {
		final String token = enterGame.getToken();

		ThreadPoolTaskExecutor taskPool = ThreadManager.me().getThreadPoolTaskExecutor("taskExecutor");
		
		String ip = session.remoteAddress().toString();
		// 登陆验证
		AccountInfo accountInfo = RemoteUtil.loginSync().loginVerify(token);

		ToolError.isAndTrue(LoginErrorCode.LOGIN_TIME_OUT, accountInfo == null);
		
		Player player = PlayerCache.me().getByUid(accountInfo.getUid());
		if (player == null) {
			// 新建角色
			player = PlayerFactory.me().poll(accountInfo);
			LogPlayerAction.me().log(player.getId(), 0,ip, LogDsp.newBuilder(PlayerActionDsp.CREATE));
			player.getPlayerProxy().setFirstLogin(true);
		} else {
			player.getPlayerProxy().setFirstLogin(false);
			// 并发加载玩家数据
			try {
				PlayerCache.me().deepLoadCache(player,taskPool.getThreadPoolExecutor());
			} catch (IllegalStateException | InterruptedException e) {
				throw ToolError.newLogicError(ArtifactErrorCode.UNKNOWN_ERROR);
			}
		}

		player.getPlayerProxy().setAccountInfo(accountInfo);
		player.getPlayerProxy().getActorRef().tell(new InternalMsg("online", ImmutableMap.of("session",session,"type","login")), ActorRef.noSender());

		RemoteUtil.loginSync().online(player.getUid());
		
		return null;
	}

	@Override
	public byte[] updateLanguage(ISession session) throws AbstractLogicModelException {
		return null;
	}

	@Override
	public byte[] setPlayerInfo(ISession session,SetPlayerInfo param) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		
		
		PlayerInfo.Builder playerBuilder = PlayerInfo.newBuilder();
		
		// 名字
		String name = param.getPlayerName();
		if (name != null) {
			ToolError.isAndTrue(GameErrorCode.CONTAINS_ILLEGAL_CHARACTERS, DirtyWordsPlugin.contains(name));
			// 如果存在换行符：会导致日志出错
			name = name.replaceAll("\r|\n", "");
			player.setName(name);
			playerBuilder.setName(player.getName());
			
			ServerCache.getPlayerInfoByPid(player.getId()).upload(MapUtil.of(org.bean.PlayerInfo.NAME, player.getName()));
			
			Map<String, Object> in = Maps.newHashMap();
			in.put(EventConditionKey.CONDITION_TYPE ,EventConditionType.CHANGE_PLAYER_NAME);
			GameEvent event = new GameEvent(player, EventType.PLAYER_CHANGE, in);
			GameEventPlugin.syncSubmit(event);
		}
		
		
		// 宣言
		String remark = param.getRemark();
		if (remark != null) {
			ToolError.isAndTrue(GameErrorCode.THE_CHARACTERS_ARE_TOO_LONG, remark.length() > 150);
			ToolError.isAndTrue(GameErrorCode.CONTAINS_ILLEGAL_CHARACTERS, DirtyWordsPlugin.contains(remark));
			player.setRemark(remark);
			playerBuilder.setRemark(player.getRemark());
		}
		
		player.update();
		player.getPlayerProxy().sendMsg(MessageManager.me().create(Core.getPlayerInfo,ProtoUnit.toByte(playerBuilder.build())));
		return new byte[0];
	}

	@Override
	public byte[] reconnect(ISession session, ReqReconnect param) throws AbstractLogicModelException {
		AccountInfo accountInfo = RemoteUtil.loginSync().loginVerify(param.getToken());
		
		Player player = PlayerCache.me().getByUid(accountInfo.getUid());
		ToolError.isAndTrue(GameErrorCode.NOR_FONT_PLAYERINFO, player==null);
		
		// 重连
		player.getPlayerProxy().setAccountInfo(accountInfo);
		player.getPlayerProxy().getActorRef().tell(new InternalMsg("online", ImmutableMap.of("session",session,"type","reconnect")), ActorRef.noSender());
		return null;
	}

	@Override
	public byte[] heartbeat(ISession session) throws AbstractLogicModelException {
		Pong.Builder builder = Pong.newBuilder();
		return builder.build().toByteArray();
	}


	@Override
	public byte[] operate(ISession session, OperateFormation msg) throws AbstractLogicModelException {
		
//		// 0 为下阵
//		ToolError.isOrTrue(GameErrorCode.FORMATION_POS_ERROR,"错误的整形位置信息", msg.getPos() < 1 , msg.getPos() > 3);

		Player player = session.getAttr(SessionConstent.PLAYER);
		Formation formation = FormationCache.me().getByPlayerIdType(player.getId(), msg.getFormationType());
		ToolError.isAndTrue(GameErrorCode.NOT_FOND_FORMATION,"阵型未找到", formation == null);
		
		List<Long> stances = formation.getStance();
		
		long sourceHeroId = "".equals(msg.getSourceHeroId()) ? 0 : Long.valueOf(msg.getSourceHeroId());
		long targetHeroId = "".equals(msg.getTargetHeroId()) ? 0 : Long.valueOf(msg.getTargetHeroId());
		
		int s_index = stances.indexOf(sourceHeroId);
		if (s_index < 0) {
			// 避免重复上阵
			if (!stances.contains(sourceHeroId)) {
				stances.add(sourceHeroId);					
			}
		}else {
			
			if (targetHeroId != 0) {
				// 交换
				ToolError.isAndTrue(GameErrorCode.FORMATION_EXCHANGE_ERROR,"交换错误", s_index < 0);
				int t_index = stances.indexOf(targetHeroId);
				if (t_index < 0) {
					// 换上没在阵型上的英雄
					stances.set(s_index, targetHeroId);
				}else {
					// 在阵型上的英雄互相交换
					stances.set(s_index, targetHeroId);
					stances.set(t_index, sourceHeroId);
				}
			}else {
				// 下阵
				ToolError.isAndTrue(GameErrorCode.FORMATION_MUST_HAVE_ONE_HERO,"阵型上必须拥有一个英雄", stances.size() <= 1);
				stances.remove(sourceHeroId);				
			}
		}
		formation.update();
		return ProtoUnit.toByte(PlayerMsgBuilder.createFormationInfo(ChangeType.UPDATE, formation));
	}
	@Override
	public void enterGame(Player player) {

	}
	@Override
	public byte[] getFormations(ISession session) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		List<Formation> formations = player.getFormationsFkPlayerId();
		FormationInfoList formationInfoList = PlayerMsgBuilder.createFormationInfoList(ChangeType.DEFAULT, formations);
		return ProtoUnit.toByte(formationInfoList);
	}


	@Override
	public byte[] getPlayerInfo(ISession session) throws AbstractLogicModelException {
		// TODO Auto-generated method stub
		return null;
	}



	@Override
	public byte[] getServerTime(ISession session, ReqServerTime reqServerTime) throws AbstractLogicModelException {
		RespServerTime.Builder builder = RespServerTime.newBuilder();
		builder.setServerTime((int)(System.currentTimeMillis()/1000));
		return builder.build().toByteArray();
	}

	@Override
	public byte[] changeHelpFightHero(ISession session, ChangeHelpFightHero param) throws AbstractLogicModelException {
		long heroId = Long.valueOf(param.getHeroId());
		Player player = session.getAttr(SessionConstent.PLAYER);
		Hero hero = player.getPlayerProxy().getHerosByDbId().get(heroId);
		ToolError.isAndTrue(GameErrorCode.NOT_FOND_HERO, hero==null);
		Hero oldHelpHero = player.getPlayerProxy().getHelpHero();
		
		
		player.getPlayerProxy().setHelpHero(hero);
		
		PlayerInfo.Builder playerBuilder = PlayerInfo.newBuilder();
		playerBuilder.setHelpFightHeroCid(hero.getCid());
		player.getPlayerProxy().sendMsg(MessageManager.me().create(Core.getPlayerInfo,ProtoUnit.toByte(playerBuilder.build())));
		
		List<Hero> updateHeroList = Lists.newArrayList();
		updateHeroList.add(oldHelpHero);
		updateHeroList.add(hero);
		player.getPlayerProxy().sendMsg(MessageManager.me().create(HeroBO.sendHeros,ProtoUnit.toByte(HeroMsgBuilder.createHeroInfoList(S2CShareMsg.ChangeType.UPDATE, updateHeroList))));
		
		Map<Integer, Object> map = Maps.newHashMap();
		map.put(org.bean.PlayerInfo.HELP_HERO_CID, hero.getCid());
		map.put(org.bean.PlayerInfo.FIGHT_POWER, hero.getHeroProxy().getFightPower());
		ServerCache.getPlayerInfoByPid(player.getId()).upload(map);
		
		return new byte[0];
	}

	@Override
	public byte[] giftCode(ISession session, GiftCode param) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
        String code = param.getCode();
        PlayerProxy playerProxy = player.getPlayerProxy();
        String osType = playerProxy.getAccountInfo().getOsType();
        int channelId = playerProxy.getAccountInfo().getChannelId();
        GiftCodeDTO dto = RemoteUtil.socialSync().gainGiftCode(player.getId(),osType,channelId, code);
        Map<Integer, Integer> out = Maps.newHashMap();
        ItemPackageHelper.unpack(dto.getItemMap(), null, out);
        List<RewardsMsg> rewards = ItemManager.unpackNotify(player, out, LogDsp.newBuilder(GoodsDsp.GIFT_CODE).addAttr("code", code));
//        ItemManager.addGoodsAndPush(player, null, null, out, LogDsp.newBuilder(GoodsDsp.GIFT_CODE).addAttr("code", code));
        return ProtoUnit.toByte(GiftCodeRps.newBuilder().addAllRewards(rewards).build());
//
//
//		Player player = session.getAttr(SessionConstent.PLAYER);
//
//		//奖励
//		LogDsp log = LogDsp.newBuilder(GoodsDsp.GIFT_CODE).targetTag(param.getCode());
//
//		List<RewardsMsg> rewards = ItemManager.unpackNotify(player, ItemManager.packGoodsByCid(600001, 1) , log);
//		return ProtoUnit.toByte(GiftCodeRps.newBuilder().addAllRewards(rewards).build());
	}

	@Override
	public byte[] reqTargetPlayerInfo(ISession session, ReqTargetPlayerInfo param) throws AbstractLogicModelException {
		
		org.bean.PlayerInfo playerInfo = RemoteUtil.socialSync().getPlayerInfo(param.getTargetPid());
		
		// 如果是本服直接提取
		if (PropManager.get(GameConstant.GAME_SERVER_ID).equals(playerInfo.getServerId())) {
			return PlayerManager.me().getLocalTargetPlayerInfo(param.getTargetPid());
		}else {
			return RemoteUtil.gameSync(playerInfo.getServerId()).getTargetPlayerInfo(param.getTargetPid());
		}
	}

	@Override
	public byte[] switchFormation(ISession session, ReqSwitchFormation param) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		
		Formation formation = FormationCache.me().getByPlayerIdType(player.getId(), param.getFormationType());
		ToolError.isAndTrue(GameErrorCode.NOT_FOND_FORMATION, formation == null);
		
		Formation oldFormation = player.getPlayerProxy().getCurrentFormation();
		oldFormation.setStatus(FormationConstant.STATUS_DEFAULT);
		
		formation.setStatus(FormationConstant.STATUS_USE);
		
		List<Formation> formations = new ArrayList<>(2);
		formations.add(oldFormation);
		formations.add(formation);
		FormationCache.me().updateBatch(formations);
		
		FormationInfoList formationInfoList = PlayerMsgBuilder.createFormationInfoList(ChangeType.UPDATE, formations);
		IMessage msg = MessageManager.me().create(Core.getFormations, formationInfoList.toByteArray());
		player.getPlayerProxy().sendMsg(msg);
		
		return new byte[0];
	}

	@Override
	public byte[] getHelpFightPlayer(ISession session) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);

		List<Integer> filterPids = Lists.newArrayList();
		filterPids.add(player.getId());
		filterPids.addAll(getNotColdStrangerFighter(player));
		RemoteSocialServer remoteSocialServer = RemoteUtil.socialSync();
		Map<Integer,org.bean.PlayerInfo> screenResult = remoteSocialServer.getHelpPlayers(player.getId(),1,filterPids);

		RepsHelpFightPlayers.Builder helpFightPlayersBuilder = RepsHelpFightPlayers.newBuilder();
		PlayerData pd = PlayerDataCache.me().getByPlayerId(player.getId());
		
		PlayerSynopsis.Builder builder = null;
		for (Entry<Integer, org.bean.PlayerInfo> e : screenResult.entrySet()) {
			builder = PlayerSynopsis.newBuilder();
			org.bean.PlayerInfo playerInfo = e.getValue();
			builder.setPid(playerInfo.getPid());
			builder.setName(playerInfo.getName());
			builder.setLvl(playerInfo.getLvl());
			builder.setHelpHeroCid(playerInfo.getHelpHeroCid());
			builder.setColdDownTime((int) (pd.getPlayerDataProxy().getDiscreteVO().getHelpFightColdDownTime(playerInfo.getPid())/1000));
			helpFightPlayersBuilder.addPlayers(builder);
		}
		
		return ProtoUnit.toByte(helpFightPlayersBuilder.build());
	}

	@Override
	public byte[] reqTest(ISession session, ReqTestMsg msg) throws AbstractLogicModelException {
		NotMsg.Builder botmsg = NotMsg.newBuilder();
		botmsg.setScore(100).setDatingType(5).setCurrentNodeId(1).setSelectedNode(7);
		
		Notes.Builder builder = Notes.newBuilder();
		
		S2CLoginMsg.Node.Builder builder2 = S2CLoginMsg.Node.newBuilder();
		builder2.setDatingId(1).addNextNodeIds(1).addNextNodeIds(2);
		builder.addNodes(builder2);
		botmsg.setNotes(builder);
		
		RespTestMsg.Builder resp = RespTestMsg.newBuilder();
		resp.addNotMsgs(botmsg).addEndings(3).addXxxx("xxx");
		return ProtoUnit.toByte(resp.build());
	}

	@Override
	public byte[] buyResources(ISession session, ReqBuyResources msg) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		PlayerData playerData = player.getPlayerDatasFkPlayerId();
		Map<Integer, ResBuyRecordVO> buyRecords = playerData.getPlayerDataProxy().getResBuyRecordVO();   

		// 取得购买记录
		ResBuyRecordVO buyRecord = buyRecords.get(msg.getCid());// ToolMap.getString(msg.getCid(), buyRecords ,System.currentTimeMillis() + "_" + 0);
		ChangeType changeType = ChangeType.UPDATE;
		if (buyRecord == null) {
			buyRecord = new ResBuyRecordVO();
			buyRecords.put(msg.getCid(), buyRecord);
			changeType = ChangeType.ADD;
		}
//		List<String> split = Lists.newArrayList();
//		split.addAll((Splitter.on('_').splitToList(buyRecord)));
		
		int boughtNum = buyRecord.getCount();
		
		ItemRecoverCfg cfg = ItemRecoverCfgCache.me().getById(msg.getCid());

		ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR, "客户端参数异常",cfg == null);
		
		ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR, cfg == null);
		
		ToolError.isAndTrue(GameErrorCode.NOT_ENOUGH_PURCHASES, "购买次数不足",(boughtNum + msg.getNum()) > cfg.getPrice().length);
		
		int startIndex = boughtNum;
		int endIndex = boughtNum + msg.getNum();
		
		int totalSellCount = 0;
		Map totalPrice = new HashMap<>();
		for (int i = startIndex; i < endIndex; i++) {
			List<Map<String, Object>> price = cfg.getPriceMap().get(i);
			
			boolean bool = true;
			for (Map<String, Object> map : price) {
				Map priceScheme = ToolMap.getMap("priceScheme", map);
				int sellCount = ToolMap.getInt("sellCount", map,0);
				bool &= ItemManager.checkGoodsByCid(player, priceScheme);
				if (bool) {
					// 价格满足
					CommonUtil.changeMap(totalPrice, priceScheme);
					totalSellCount+=sellCount;
					break;
				}
			}
			ToolError.isAndTrue(GameErrorCode.ITEM_NOT_ENOUGH, "道具不足", !bool);
		}
		
		LogDsp log = LogDsp.newBuilder(GoodsDsp.BUY_RESOURCES).targetTag(cfg.getItemId());
		
		ItemManager.costGoodsByCid(player, totalPrice, log, S2CItemMsg.ItemList.newBuilder());
		
		ItemManager.addGoodsAndPush(player, null, null, MapUtil.of(cfg.getItemId(), totalSellCount), LogDsp.newBuilder(GoodsDsp.BUY_RESOURCES));
		
		buyRecord.setCount(endIndex);
		playerData.update();
		
		player.getPlayerProxy().startSecondsJob();
		
		// 更新购买记录
		BuyResourcesLog logs = ResourceLogMsgBuilder.buildResourceLogMsg(changeType, msg.getCid(),endIndex);
		RespBuyResourcesLog resp = RespBuyResourcesLog.newBuilder().addLogs(logs).build();
		IMessage outMsg = MessageManager.me().create(Core.buyResourcesLog, ProtoUnit.toByte(resp));
		session.sendMessage(outMsg);
		
		
		Map<String, Object> in = Maps.newHashMap();
		in.put(EventConditionKey.CONDITION_TYPE, EventConditionType.BUY_RESOURCE);
		in.put(EventConditionKey.RESOURCE_CID, cfg.getId());
		GameEvent event = new GameEvent(player, EventType.ITEM_EVENT, in);
		GameEventPlugin.syncSubmit(event);
		return ProtoUnit.toByte(PlayerMsgBuilder.buildRespBuyResourcesMsg(msg.getCid(),msg.getNum()));
	}


	@Override
	public byte[] buyResourcesLog(ISession session, ReqBuyResourcesLog msg) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		PlayerData playerData = player.getPlayerDatasFkPlayerId();
		Map<Integer, ResBuyRecordVO> buyRecords = playerData.getPlayerDataProxy().getResBuyRecordVO();   
		
		List<BuyResourcesLog> logs = ResourceLogMsgBuilder.buildResourceLogMsg(ChangeType.DEFAULT, buyRecords);
		RespBuyResourcesLog resp = RespBuyResourcesLog.newBuilder().addAllLogs(logs).build();

		return ProtoUnit.toByte(resp);
	}

	@Override
	public byte[] reqNewPlayerGuide(ISession session, C2SPlayerMsg.ReqNewPlayerGuide msg) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		PlayerData pd = player.getPlayerDatasFkPlayerId();
		DiscreteVO discreteVO = pd.getPlayerDataProxy().getDiscreteVO();
		discreteVO.setNewPlayerGuide(msg.getData());
		// 新手引导日志
		LogPlayerAction.me().playerGuideLog(player.getId(), msg.getData(), LogDsp.newBuilder(PlayerActionDsp.NEW_PLAYER_GUIDE));
		pd.getPlayerDataProxy().save();
		return new byte[0];
	}

	@Override
	public byte[] recordClientErr(ISession session, C2SPlayerMsg.RecordClientErr msg) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		LogClientErr.me().log(player.getId(),msg.getErr());
		return new byte[0];
	}

	@Override
	public byte[] getFunctionSwitch(ISession session) throws AbstractLogicModelException {
		Collection<FunctionSwitchDTO> all = FunctionSwitchCache.getAllCache();
		return ProtoUnit.toByte(FunctionSwitchMsgBuilder.buildRespFunctionSwitch(all));
	}


	@Override
	public byte[] uploadSettings(ISession session, Settings settings) throws AbstractLogicModelException {
		Player player = session.getAttr(SessionConstent.PLAYER);
		PlayerData pd = player.getPlayerDatasFkPlayerId();
		DiscreteVO discreteVO = pd.getPlayerDataProxy().getDiscreteVO();
		discreteVO.setSettings(settings.getData());
		pd.getPlayerDataProxy().save();
		return new byte[0];
	}

	/**
	 * 获取未冷却助战路人
	 */
	private List<Integer> getNotColdStrangerFighter(Player player){
		PlayerDataProxy pdp = player.getPlayerDatasFkPlayerId().getPlayerDataProxy();
		List<Integer> result = Lists.newArrayList();
		List<Integer> outTimeList = Lists.newArrayList();
		int cd = DiscreteDataCfgCache.me().getIntData(DiscreteDataID.HELP_FIGHTER,DiscreteDataKey.HELP_CD);
		Date now = new Date();
		pdp.getDiscreteVO().getHelpFighterColdTimeMap().forEach((k,v)->{
			if (FightManager.me().isHelpFightColdDown(player,k,now)){
				result.add(k);
			}else{
				outTimeList.add(k);
			}
		});
		if (outTimeList.size() > 0){
			outTimeList.forEach(id->pdp.getDiscreteVO().getHelpFighterColdTimeMap().remove(id));
		}
		return result;
	}
}
